package com.zyh.demo.homework.test2;

import com.zyh.demo.homework.test2.domain.Student;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.FileReader;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author zyh
 * @Date 2024/8/14 19:33
 * @Description
 */

public class ReaderXML {
    public static void main(String[] args) throws Exception {
        //读取xml文件
        SAXReader saxReader = new SAXReader();
        Document read = saxReader.read(new FileReader("D:\\Code\\IDEA\\idea_projects\\JavaSE-plus\\day16-code\\src\\com\\zyh\\demo\\homework\\test2\\Student.xml"));
        //获取根节点元素
        Element rootElement = read.getRootElement();
        //获取所有子标签元素
        List<Element> ziElements = rootElement.elements();
        //创建Student字节码对象
        Class c = Student.class;
        //获取构造方法
        Student student = (Student) c.getDeclaredConstructor().newInstance();
        Field[] declaredFields = c.getDeclaredFields();
        //遍历集合获取每个子标签
        for (Element ziElement : ziElements) {
            //创建一个集合
            List<String> list = new ArrayList<>();
            //获取每个子标签的孙子标签
            List<Element> sunElements = ziElement.elements();
            //遍历集合拿到每个孙子标签
            for (Element sunElement : sunElements) {
                //拿到孙子标签名和值
                String name = sunElement.getName();
                String text = sunElement.getText();
                //将值存入集合中
                list.add(text);
            }
            for (int i = 0; i < list.size(); i++) {
                declaredFields[i].setAccessible(true);
                if (declaredFields[i].getType().getName().contains("String")) {
                    declaredFields[i].set(student, list.get(i));
                } else if (declaredFields[i].getType().getName().contains("Integer")) {
                    int IntegerValue = Integer.parseInt(list.get(i));
                    declaredFields[i].set(student, IntegerValue);
                }
            }
            System.out.println(student);
        }
    }
}

